import 'package:flutter/material.dart';

class KeepAliveWidget extends StatefulWidget {
  final Widget child;
  final bool keepAlive;

  const KeepAliveWidget(this.child, {super.key, this.keepAlive = true});

  @override
  State<StatefulWidget> createState() => KeepAliveState();
}

class KeepAliveState extends State<KeepAliveWidget>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => widget.keepAlive;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.child;
  }

  @override
  void didUpdateWidget(covariant KeepAliveWidget oldWidget) {
    if (oldWidget.keepAlive != widget.keepAlive) {
      // keepAlive 状态需要更新，实现在 AutomaticKeepAliveClientMixin 中
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }
}

Widget keepAliveWrapper(Widget child) {
  return KeepAliveWidget(child);
}
